package com.gxgeek.lock;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author gaoxing
 * @create 2017-12-19 上午11:34
 */
public class ReentrantReadWriteLockDemoTwo {
    private static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();

    private static Lock w = lock.writeLock();

    private static Lock r = lock.readLock();

    public static void main(String[] args) {
        News news = new News();
        //write and get
        new Thread(new Runnable() {
            @Override
            public void run() {
                for(int  i = 0; i < 5; i++){
                    w.lock();
                    news.add(i + "");
                    r.lock();
                    w.unlock();
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    String s = news.getLast();
                    System.out.println(Thread.currentThread().getName() + " get the last news" + s);
                    r.unlock();
                }
            }
        }, "WriteAndGetThread").start();


        //write
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
//                Thread.yield();
                for(int  i = 5; i < 10; i++){
                    w.lock();
                    news.add(i + "");
                    w.unlock();
                }
            }
        }, "WriteThread");
        t.start();

    }

    static class News {

        private final List<String> newsList = new ArrayList<>();

        public String getLast(){
            if(newsList.size() == 0)
                return null;
            return newsList.get(newsList.size() - 1);
        }

        public void add(String news) {
            newsList.add(news);
            System.out.println(Thread.currentThread().getName() + " add :" + news);
        }
    }

}
